#!/bin/bash

# OpenHarmony Build Manager (bl) - 卸载脚本

set -e

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}OpenHarmony Build Manager (bl) 卸载程序${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

USER_BIN="$HOME/bin"
BL_SCRIPT="$USER_BIN/bl"
BASE_DIR="$HOME/openharmony"
BASH_COMPLETION="$HOME/.local/share/bash-completion/completions/bl"
ZSH_COMPLETION="$HOME/.zsh/completions/_bl"

# 检查 bl 是否已安装
if [ ! -f "$BL_SCRIPT" ]; then
    echo -e "${YELLOW}⚠ bl 工具未安装${NC}"
    exit 0
fi

echo -e "${BLUE}将要删除:${NC}"
echo "  • 命令: $BL_SCRIPT"
[ -f "$BASH_COMPLETION" ] && echo "  • Bash 补全: $BASH_COMPLETION"
[ -f "$ZSH_COMPLETION" ] && echo "  • Zsh 补全: $ZSH_COMPLETION"
echo ""
echo -e "${GREEN}注意: 代码数据将会保留${NC}"
echo "  - 代码目录: $BASE_DIR/code_download"
echo "  - 工作目录: $BASE_DIR/workspace"
echo ""

read -r -p "确认卸载 bl 命令? [y/N]: " confirm

if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
    echo -e "${BLUE}已取消${NC}"
    exit 0
fi

echo ""
echo -e "${BLUE}开始卸载...${NC}"

# 删除 bl 命令
if [ -f "$BL_SCRIPT" ]; then
    rm -f "$BL_SCRIPT"
    echo -e "${GREEN}✓ 已删除 bl 命令${NC}"
fi

# 删除补全脚本
if [ -f "$BASH_COMPLETION" ]; then
    rm -f "$BASH_COMPLETION"
    echo -e "${GREEN}✓ 已删除 Bash 补全脚本${NC}"
fi

if [ -f "$ZSH_COMPLETION" ]; then
    rm -f "$ZSH_COMPLETION"
    echo -e "${GREEN}✓ 已删除 Zsh 补全脚本${NC}"
fi

echo ""

# 检查并删除定时任务
echo -e "${BLUE}正在删除定时任务...${NC}"
if crontab -l 2>/dev/null | grep -q "$HOME/bin/bl"; then
    # 删除包含 bl 的定时任务
    crontab -l 2>/dev/null | grep -v "$HOME/bin/bl" | crontab -
    echo -e "${GREEN}✓ 定时任务已删除${NC}"
else
    echo -e "${BLUE}未找到相关定时任务${NC}"
fi

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}✓ 卸载完成！${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

echo -e "${BLUE}已保留的文件:${NC}"
echo "  • 代码数据: $BASE_DIR"
echo "  • 分支配置: $BASE_DIR/.bl_branches"
echo "  • 认证配置: $HOME/.repo_env"
echo ""
echo -e "${YELLOW}如需完全清理，请手动执行:${NC}"
echo "  rm -rf $BASE_DIR"
echo "  rm -f $HOME/.repo_env"
echo ""
